package com.unionftech.content_login.service

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.unionftech.common.base.mvp.impl.IBaseCallBack
import com.unionftech.common.bean.ApiException
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.bean.toastTimeout
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.router.RouterPath
import com.unionftech.common.router.service.ILoginService
import com.unionftech.common.utils.ActivityCollector
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.SpUtils
import com.unionftech.common.utils.ToastUtils
import com.unionftech.content_login.api.interceptor.ITokenRefresh
import com.unionftech.content_login.bean.LoginTokenInfo
import com.unionftech.content_login.bean.ThirdLoginWay
import com.unionftech.content_login.bean.toastRemoteWarning
import com.unionftech.content_login.model.LoginModel
import com.unionftech.content_login.ui.login.UFLoginActivity
import com.unionftech.content_login.ui.register.UFRegisterActivity
import com.unionftech.content_login.util.QuickLoginUtil
import com.unionftech.content_login.util.TokenManager
import com.unionftech.common.R.string

@Route(
    path = RouterPath.LoginServiceInfo.PATH, name = RouterPath.LoginServiceInfo.NAME
)
class LoginServiceImpl : ILoginService, ITokenRefresh {
    private lateinit var mContext: Context
    private val mLoginModel by lazy { LoginModel() }

    override fun init(context: Context?) {
        if (context == null) {
            throw RuntimeException("init service first")
        }
        LogUtils.d("LoginServiceImpl 初始化完成 >>>")
        mContext = context
        //如果用户未登录，就进行一键登录预取号,退出登录的时候不需要重新取号
        QuickLoginUtil.getInstance().init(mContext)
        if (!checkLogin()) {
            QuickLoginUtil.getInstance().prefetchMobileNumber()
        }
    }

    /**
     * 获取网易一键登录预取号状态
     */
    override fun prefetchMobileState(): Boolean {
        return QuickLoginUtil.getInstance().prefetchMobileState()
    }

    /**
     * 检查登录状态
     */
    override fun checkLogin(): Boolean {
        val login = TokenManager.getInstance().isLogin()
        return login
    }

    /**
     * 获取用户登录的Token
     */
    override fun getUserToken(): String {
        return TokenManager.getInstance().getAccessToken()
    }

    /**
     * 跳转登录界面
     */
    override fun gotoLogin() {
        val loginWay = SpUtils.getInstance().getString(LoginConstants.Key.LOGIN_WAY)
        if (TextUtils.isEmpty(loginWay) || loginWay == LoginConstants.Constant.LOGIN_BY_QUICK) {
            //如果登录方式没有确定，则首先调用一键登录界面
            //如果是一键登录先跳转一键登录界面，如果跳转失败则跳转账号密码登录界面
            gotoQuickLogin()
            ActivityCollector.finishAll()
        } else {
            //跳转账号密码登录页
            gotoAccountLogin()
        }
    }

    override fun logout(callBack: ((Boolean) -> Unit)?) {
        //首先进行预约取号
        QuickLoginUtil.getInstance().prefetchMobileNumber {
            val loginWay = SpUtils.getInstance().getString(LoginConstants.Key.LOGIN_WAY)
            when (loginWay) {
                LoginConstants.Constant.LOGIN_BY_GOOGLE -> {
                    googleLogout()
                }
            }
            appLogout(callBack)
        }
    }


    override fun gotoRegister() {
        UFRegisterActivity.startThis(mContext)
    }

    override fun gotoGoogleLogin() {
        GoogleCredentialManagerSign.googleLogin(mContext) { idToken ->
            verifyThirdLogin(mContext, ThirdLoginWay.LOGIN_BY_GOOGLE, idToken, "")
        }
    }

    override fun googleLogout() {
        GoogleCredentialManagerSign.googleLogout()
    }

    override fun getHeaderTokenKey(): String {
        return TokenManager.getInstance().getHeaderTokenKey()
    }

    override fun isTokenExpired(responseBodyString: String): Boolean {
        return TokenManager.getInstance().isTokenExpired(responseBodyString)
    }

    override fun clearExpiredToken(): String {
        return TokenManager.getInstance().clearExpiredToken()
    }

    override fun asyncRefreshToken(token: String): Any? {
        val any = TokenManager.getInstance().asyncRefreshToken(token)
        LogUtils.d("LoginServiceImpl", "asyncRefreshToken-->${any}")
        if (any is String && any == ResponseResult.LOGIN_EXPIRED) {
            //登录超时提示
            LogUtils.d("LoginServiceImpl", "asyncRefreshToken 登录超时提示")
            Handler(Looper.getMainLooper()).postDelayed({
                ToastUtils.longToast(
                    DynamicResourceManager.getString(mContext, string.login_timeout)
                )
            }, 500)
            return null
        }
        return any
    }


    override fun saveToken(t: Any) {
        if (t is LoginTokenInfo) {
            TokenManager.getInstance().saveToken(t)
        }
    }

    override fun getAccessToken(): String {
        return TokenManager.getInstance().getAccessToken()
    }

    override fun needLogin() {
        TokenManager.getInstance().clearTokenInfo()
        gotoLogin()
    }


    /**
     * 打开一键登录授权页
     */
    private fun gotoQuickLogin() {
        QuickLoginUtil.getInstance().onePass(mContext) { token, accessToken ->
            if (TextUtils.isEmpty(token) || TextUtils.isEmpty(accessToken)) {
                if (!QuickLoginUtil.getInstance().prefetchMobileState()) {
                    gotoAccountLogin()
                }
            } else {
                verifyThirdLogin(mContext, ThirdLoginWay.LOGIN_BY_NETEASE, token!!, accessToken!!)
            }
        }
    }

    private fun gotoAccountLogin() {
        LogUtils.d("gotoAccountLogin--->")
        UFLoginActivity.startThis(mContext)
        ActivityCollector.finishAll()
    }

    private fun verifyThirdLogin(
        context: Context,
        loginWay: ThirdLoginWay,
        ydToken: String,
        accessToken: String,
    ) {
        LogUtils.d(
            "LoginServiceImpl", "verifyThirdLogin ydToken:${ydToken} \n accessToken:$accessToken"
        )
        mLoginModel.thirdlogin(ydToken,
            accessToken,
            loginWay.type,
            object : IBaseCallBack<ResponseResult<Any?>> {
                override fun onResponse(response: ResponseResult<Any?>) {
                    when (response.code) {
                        //登录成功或注册且登录成功
                        ResponseResult.SUCCESS_CODE, LoginConstants.Code.REGISTER_LOGIN_SUCCESS, LoginConstants.Code.REMOTE_LOGIN_WARNING -> {
                            //注册且登录成功
                            if (response.code == LoginConstants.Code.REGISTER_LOGIN_SUCCESS) {
                                response.toast()
                            } else if (response.code == LoginConstants.Code.REMOTE_LOGIN_WARNING) {
                                //异地登录提示
                                response.data?.also {
                                    val loginTokenInfo = it as LoginTokenInfo
                                    loginTokenInfo.toastRemoteWarning()
                                }
                            }
                            //一键登录成功，跳转首页
                            gotoMainAndSaveLoginWay(loginWay)
                        }

                        else -> {
                            if (ApiException.isTimeout(response.code)) {
                                response.toastTimeout()
                            } else {
                                //toast一键登录失败的信息提示
                                response.toast(
                                    DynamicResourceManager.getString(
                                        context, string.login_failed
                                    )
                                )
                            }
                        }
                    }
                }
            })
    }

    private fun gotoMainAndSaveLoginWay(loginWay: ThirdLoginWay) {
        gotoMain()
        when (loginWay) {
            ThirdLoginWay.LOGIN_BY_NETEASE -> {
                //记录本次登录方式为一键登录
//                SpUtils.getInstance().put(
//                    LoginConstants.Key.LOGIN_WAY, LoginConstants.Constant.LOGIN_BY_QUICK
//                )
                //主动关闭授权页
                QuickLoginUtil.getInstance().quitActivity(mContext)
            }

            ThirdLoginWay.LOGIN_BY_GOOGLE -> {
                //记录本次登录方式为Google登录,退出的时候，清除google授权
                SpUtils.getInstance()
                    .put(LoginConstants.Key.LOGIN_WAY, LoginConstants.Constant.LOGIN_BY_GOOGLE)
            }
        }
    }

    private fun gotoMain() {
        ARouter.getInstance().build(RouterPath.UFUFMainStandardActivityInfo.PATH).navigation()
        ActivityCollector.finishAll()
    }

    private fun appLogout(callBack: ((Boolean) -> Unit)?) {
        mLoginModel.logout(object : IBaseCallBack<ResponseResult<Any?>> {
            override fun onResponse(response: ResponseResult<Any?>) {
                TokenManager.getInstance().clearTokenInfo()
                if (response.code == ResponseResult.SUCCESS_CODE) {
                    callBack?.invoke(true)
                } else {
                    callBack?.invoke(false)
                }
            }
        })
    }
}